/**
 * 
 */
package org.compiere.process;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Properties;
import java.util.TimeZone;
import java.util.logging.Level;
import org.compiere.model.Mhrmlimitholiday;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.joda.time.DateTime;

/**
 * The process for adding a new limit on leave on a certain date
 * @author V.Sokolov
 *
 */
public class GenerateLimitHoliday extends SvrProcess {
	
	/** Current context	*/
	private Properties m_ctx;
	/** */
	private DateTime currentDate = new DateTime();
	/** */
	private Timestamp dateFrom;
	/** */
	Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); 

	/* 
	 */
	@Override
	protected void prepare() {
		
		log.info("Start generate limit holiday");
		m_ctx = Env.getCtx();

		ProcessInfoParameter[] para = getParameter();
		for (int i = 0; i < para.length; i++)	{
			String name = para[i].getParameterName();
			if (name == null); 
				//
			else if (name.compareTo("DateFrom") == 0){
				dateFrom = (Timestamp) para[i].getParameter();
				currentDate = new DateTime(dateFrom.getTime());
			}
			else
				log.log(Level.INFO, "Unknown Parameter: " + name);
		}
		
		currentDate = currentDate.minusDays(1);
	}

	/* 
	 */
	@Override
	protected String doIt() throws Exception {
		
		calendar.setTimeInMillis(currentDate.getMillis());
		calendar.add(Calendar.YEAR, +1);
		
		StringBuffer employee = new StringBuffer("Employee: ");

		// The list of employees to new limits
		Mhrmlimitholiday[] limits = getLinesLimits();
		
		int n = 0;
		for(Mhrmlimitholiday l: limits){
			Mhrmlimitholiday lim = new Mhrmlimitholiday(m_ctx, 0, get_TrxName());
			// clone
			Mhrmlimitholiday.copyValuesLimit(l, lim);
			l.setIsActive(false);
			l.saveEx();	
			lim.sethrm_limitdays(l.gethrm_limitdays()+Mhrmlimitholiday.LIMIT_VACATIONS+l.gethrm_days().intValue());
			lim.sethrm_daysused(0);
			lim.sethrm_order_ID(0);
			lim.setStartDate(new Timestamp(currentDate.getMillis()));
			lim.setEndDate(new Timestamp(calendar.getTimeInMillis()));
			lim.saveEx();
			n++;
			// list employee
			employee.append(n+"->"+l.getC_BPartner().getLastName()+" "+l.getC_BPartner().getFirstName().substring(0, 1)+".; ");
		}
		
		return Msg.translate(m_ctx, "Success")+
				". Number of records: "+n+
				" on the date: "+currentDate.toString()+
				". "+employee.toString();
	}
	
	private Mhrmlimitholiday[] getLinesLimits(){
		
		ArrayList<Mhrmlimitholiday> list = new ArrayList<Mhrmlimitholiday>();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT * FROM HRM_LIMITHOLIDAY \n");
		sql.append("JOIN C_BPARTNER ON C_BPARTNER.C_BPARTNER_ID=HRM_LIMITHOLIDAY.C_BPARTNER_ID \n");
		sql.append("WHERE HRM_LIMITHOLIDAY.ENDDATE = "+DB.TO_DATE(new Timestamp(currentDate.getMillis()), true)+" \n");
		sql.append("AND HRM_LIMITHOLIDAY.ISACTIVE='Y' \n");
		sql.append("AND C_BPARTNER.ISACTIVE='Y'");
		
		try
		{
			pstmt = DB.prepareStatement(sql.toString(), get_TrxName());
			rs = pstmt.executeQuery();	
					
			while (rs.next ())
				list.add(new Mhrmlimitholiday(m_ctx, rs, get_TrxName()));

		}
		catch (SQLException e)
		{
			log.log(Level.SEVERE, "product", e);
		}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}	
		
		return list.toArray(new Mhrmlimitholiday[list.size()]);
	}

}
